package com.leetcode.solution.s8x;

import java.util.HashMap;
import java.util.Map;

public class Scramble87Bak {
    public static void main(String[] args) {
        boolean flag = new Scramble87Bak().isScramble("eebaacbcbcadaaedceaaacadccd", "eadcaacabaddaceacbceaabeccd");

        System.out.println(flag);
    }

    public boolean isScramble(String s1, String s2) {
        Map<String, Boolean> historyResult = new HashMap<>();
        return isScramble(s1,s2,historyResult);
    }

    private boolean isScramble(String s1, String s2, Map<String, Boolean> historyResult) {
        if (historyResult.containsKey(s1 + "#" + s2)) {
            return historyResult.get(s1 + "#" + s2);
        }

        if (s1.length() != s2.length()) {
            historyResult.put(s1 + "#" + s2, false);
            return false;
        } if (s1.equals(s2)) {
            historyResult.put(s1 + "#" + s2, true);
            return true;
        }

        int len = s1.length();
        int[] letters = new int[26];
        for (int i = 0; i < len; i++) {
            letters[s1.charAt(i) - 'a']++;
            letters[s2.charAt(i) - 'a']--;
        }

        for (int letter : letters) {
            if (letter != 0) {
                historyResult.put(s1 + "#" + s2, false);
                return false;
            }
        }

        for (int i = 1; i < len; i++) {
            if ( (isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i), s2.substring(i))) ||
                    ((isScramble(s1.substring(0, i), s2.substring(len - i)) && isScramble(s1.substring(i), s2.substring(0, len - i)))) ) {
                historyResult.put(s1 + "#" + s2, true);
                return true;
            }
        }

        historyResult.put(s1 + "#" + s2, false);
        return false;
    }
}
